#!/usr/bin/php
<?php

function test($fp, $sem, $str)
{
    for ($i = 1; $i <= 100; ++$i) {
        sem_acquire($sem);
        $s = sprintf("%s pid = %d, count = %d\n", $str, posix_getpid(), $i);
        $l = strlen($s);
        for ($j = 0; $j < $l; ++$j) {
            fwrite($fp, $s[$j]);
        }
        sem_release($sem);
    }
}

function main($argc, & $argv)
{
    $sem = sem_get(ftok("/kyo", "C"));

    $fp = fopen("test_file", "w");

    if (pcntl_fork() == 0) {
        test($fp, $sem, "child");
        exit(0);
    }
    test($fp, $sem, "parent");
    pcntl_wait($status);

    sem_remove($sem);

    return 0;
}

exit(main($argc, $argv));

